package com.cyc.lock;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 自旋锁
 */
public class SpinlockDemo {


    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    //加锁
    public void mylock(){
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName()+"===>尝试得到mylock");
        //自旋锁 直到加锁成功
        while (!atomicReference.compareAndSet(null,thread)){

        }
        System.out.println(thread.getName()+"===>得到mylock成功");
    }

    //解锁
    public void myunlock(){
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName()+"===>myunlock");
        atomicReference.compareAndSet(thread,null);
    }
}
